package com.wzy.service.impl;


import com.wzy.feign.ProductFeignClient;
import com.wzy.order.bean.Order;
import com.wzy.product.bean.Product;
import com.wzy.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;

@Service
@Slf4j
public class OrderServiceImpl implements OrderService {

    @Autowired
    ProductFeignClient productFeignClient;
    @Override
    public Order createOrder(Long productId, Long userId) {
//        Product prodyctFromRemote = getProdyctFromRemote(productId);
        Product product = productFeignClient.getProductById(productId);
        Order order = new Order();

       order.setId(1l);
//       总金额
       order.setTotalAmount(product.getPrice().multiply(new BigDecimal(product.getNum())));
       order.setUserId(userId);
       order.setNickName("zhangsan");
       order.setAddress("dizhi");
//       远程查询商品列表
       order.setProductList(Arrays.asList(product));
       return order;
    }

    @Autowired
    DiscoveryClient discoveryClient;

    @Autowired
    LoadBalancerClient loadBalancerClient;





    private Product getProdyctFromRemote(Long productId){
        //1. 获取到商品服务所在的所有机器Ip+port
//        ServiceInstance choose = loadBalancerClient.choose("service-product");//有负载均衡的
//        List<ServiceInstance> instances = discoveryClient.getInstances("service-product");
//        ServiceInstance serviceInstance = instances.get(0);
//        String url = "http://"+choose.getHost() + ":" +choose.getPort()+"/product/"+productId;
//        log.info("远程请求: {}",url);
        String url = "http://service-product/product/"+productId;//基于注解的 service-product会被动态替换
//      //2. 给远程发送请求
        RestTemplate restTemplate = new RestTemplate();//线程安全 建议放进容器
        Product forObject = restTemplate.getForObject(url, Product.class);
        return forObject;
    }
}
